# coding=utf-8 ##��utf-8���봢�������ַ�

import socket, time,threading,string, thread
import SocketServer,math,sys, time,os
from Configuration import Configuration

enableRunFlag = True;
Configuration = Configuration()
port = 19976
pid = 0
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
hostAddr = "fs3.das3.tudelft.nl"

"""
Registration registryServer for registering client and registryServer which need to execute binary files.
"""
def registryServer(num_prun_machine,num_openttd_client):
    try:
        enableRunFlag = True
        print "------------start registryServer -----------------------------", time.time()
        print "-------------expect %d clients------------------------"%num_prun_machine
        global s
        s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.bind(("",port))
        s.listen(50)
        connections = 0;
        list = []
        total = num_openttd_client
        global pid
        pid = os.getpid()
        while(enableRunFlag):
            con,addr = s.accept();
            print "accept #%d"%len(list), addr
            connections = connections + 1;
            str = con.recv(1024)
            con.settimeout(10)
            list.append((con,addr,str))
            if len(list) == 1: #The first one connect to this registry server is app server
                con.send("registryServer")
                serveraddress = str
            else:
                machines = num_prun_machine - len(list) + 1
                each = math.ceil(total//machines)
                print total, each, machines
                total = total - each
                con.send(serveraddress + " %d"%each)
            con.close()
            if num_prun_machine - len(list) == 0:
                break
        s.close()
        print "----------------stop registryServer -----------------------------", time.time()
    finally :
        s.close()
#        if(len(list) == num_prun_machine):
#            list[0][0].send("server")
#            serveraddress = list[0][2]
#            for i in range(1, len(list)):
#                machines = len(list) - i
#                each = math.ceil(total//machines)
#                print total, each, machines
#                total = total - each
#                list[i][0].send( serveraddress + " %d"%each)
#            break
#    for i in range(0, len(list)):
#        list[i][0].close()

def start_server(num_prun_machine, num_openttd_client):
    try:
        thread.start_new_thread(registryServer, (num_prun_machine,num_openttd_client))
    except:
        pass
def start_client():
    thread.start_new_thread(client,(hostAddr,))
    
def client(ipAddress=hostAddr):
    try:
        hostname = Configuration.getHostName();
        print hostname, "client connecting", ipAddress
        s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.connect((ipAddress,port))
        s.settimeout(5)
        hostname = Configuration.getHostName()
        s.send(hostname)
        
        content = s.recv(1024)
        tup = string.split(content)
        s.close()
        return tup
    except:
        return (0,)

if __name__ == "__main__":
    prun = 16
    registryServer(prun, 20)
    

#    time.sleep(2)
    
#    start_client()
#    start_client()
#    start_client()
#    start_client()
#    start_client()
#class server_thread(threading.Thread):
#    networkFileName = ""
#    running = False
#    def __init__(self):
#        threading.Thread.__init__(self)
#    
#    def setConnection(self, connection):
#        self.con = connection
#
#    def run(self):
#        


